<template>
  <div>
    <el-form :model="form" label-width="130px" :rules="rules" ref="form" style="margin-top: -12px">
      <el-form-item label="价格设置" class="one-label">

        <el-form-item v-show="form.skuFlag == 0" label="外部编码：" label-width="170px">
          <el-input v-model="form.externalCode" class="short-input width-per-50">
          </el-input>
        </el-form-item>

        <el-form-item v-show="form.skuFlag == 0" label="供应价：" label-width="170px" prop="supplyPrice">
          <el-input v-model="form.supplyPrice" class="short-input width-per-50"
            @keyup.native="form.supplyPrice = checkInputNum(form.supplyPrice)" placeholder="例如：100">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <template v-if="supplierConfig.warehouseAuthority == 1">
          <el-form-item label="供应价含税：" label-width="170px" prop="supplierTaxFlag">
            <el-select v-model="form.supplierTaxFlag">
              <el-option label="已含税" value="1"></el-option>
              <el-option label="未含税" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="进项税税目：" label-width="170px" prop="taxItemsId">
            <el-select v-model="form.taxItemsId">
              <el-option label="无" value=""></el-option>
              <el-option v-for="item in taxList" :key="item.taxItemsId"
                :label="item.taxName + '(' + item.taxRate + '%)'" :value="item.taxItemsId"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="供应商运费：" label-width="170px">
          <el-input v-model="form.supplierPostFee" class="short-input width-per-50" min="0">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item v-show="form.skuFlag == 0" label="划线价：" label-width="170px" prop="scribingPrice">
          <el-input v-model="form.scribingPrice" class="short-input width-per-50"
            @keyup.native="form.scribingPrice = checkInputNum(form.scribingPrice)" placeholder="例如：100">
            <template slot="append">元</template>
          </el-input>
          <div class="tips">划线价在商品详情会以划线形式显示</div>
        </el-form-item>
        <el-form-item v-show="form.skuFlag == 1" label="商品规格：" label-width="170px">
          <div v-if="!(supplierGoodsId && stockBoolean)" v-for="(item, index) in form.qualityData" :key="index"
            class="quality-bar mar-b-15">
            <div class="mar-b-20 position-r qta-item flex">
              <span class="flex-item">
                <el-select v-model="item.skuPropName" placeholder="请选择" @change="changeSelect(index)" ref="select">
                  <el-option v-for="item in categorySkuList" :key="item.skuPropName" :label="item.skuPropName"
                    :value="item.skuPropName" :disabled="item.disabled"></el-option>
                  <el-option style="padding: 0" value="">
                    <el-button style="width: 100%; border: none; " icon="el-icon-plus" @click="addSku(item)">添加主规格</el-button>
                  </el-option>
                </el-select>
              </span>
              <i class="el-icon-error font-26 close-quality" v-if="!(supplierGoodsId && stockBoolean)"
                @click="removeQta(item, index)"></i>
            </div>
            <el-row :gutter="20" class="pad-l-30 pad-r-30">
              <el-col :span="8" v-for="(subItem, subIndex) in item.skuPropValueList" :key="subIndex"
                class="flex v-align-c mar-b-10">
                <span class="flex-item mar-r-10 position-r">
                  <el-input v-model="subItem.skuPropValue" class="width-per-100" placeholder="子规格名称（比如：红色）"
                    @blur="subInputBlur"></el-input>
                  <i v-if="!(supplierGoodsId && stockBoolean)" class="el-icon-error close-sub"
                    @click="removeSubQta(item.skuPropValueList, subIndex)"></i>
                </span>
                <template v-if="(subIndex + 1 == item.skuPropValueList.length) && !(supplierGoodsId && stockBoolean)">
                  <span class="font-14 font-blue" @click="addSubQta(item)">添加子规格</span>
                </template>
              </el-col>
            </el-row>
          </div>
          <div v-if="!(supplierGoodsId && stockBoolean)">
            <el-button type="primary" size="small" @click="addQta">添加规格</el-button>
          </div>
          <div class="table-container pad-t-20 pad-b-20">
            <div
              class="el-table el-table--fit el-table--border el-table--enable-row-hover el-table--medium el-table--scrollable-x">
              <div class="el-table__body-wrapper">
                <table cellspacing="0" cellpadding="0" border="0" class="el-table__body" style="width: 100%">
                  <thead class="el-table__header">
                    <tr>
                      <template v-for="(item, indexTh) in form.qualityData">
                        <th width="135" :key="'indexTh-' + indexTh">
                          <div class="cell text-align-c">
                            {{ item.skuPropName }}
                          </div>
                        </th>
                      </template>
                      <th width="135">
                        <div class="cell text-align-c">图片</div>
                      </th>
                      <th width="135">
                        <div class="cell text-align-c">
                          <el-popover placement="top" width="160" v-model="visiblePopScribingPrice">
                            <div class="text-align-c pad-b-10">批量设置</div>
                            <el-form label-position="right" style="width: 100%">
                              <el-form-item>
                                <el-input v-model="skuParamSettingValue"
                                  @keyup.native=" skuParamSettingValue = checkInputNum(skuParamSettingValue)"
                                  type="number" />
                              </el-form-item>
                            </el-form>
                            <div class="mar-t--10" style="text-align: right">
                              <el-button size="mini" type="text" @click="visiblePopScribingPrice = false">取消</el-button>
                              <el-button type="primary" size="mini" @click="batchUpdateSkuParamPrice">确定</el-button>
                            </div>
                            <label slot="reference" @click="editSkuParam('4')">
                              <span>划线价</span>
                              <i class="el-icon-circle-plus mar-l-10 font-blue"></i>
                            </label>
                          </el-popover>
                        </div>
                      </th>
                      <th width="135">
                        <div class="cell text-align-c">供应价(元)</div>
                      </th>
                      <th width="135">
                        <div class="cell text-align-c">
                          <template v-if="stockBoolean || form.crossBorderType === '2'">
                            <div class="cell text-align-c">库存</div>
                          </template>
                          <template v-else>
                            <el-popover placement="top" width="160" v-model="visiblePopStock">
                              <div class="text-align-c pad-b-10">批量设置</div>
                              <el-form label-position="right" style="width: 100%">
                                <el-form-item>
                                  <el-input v-model="skuParamSettingValue"
                                    @keyup.native=" skuParamSettingValue = checkInputPositiveNum(skuParamSettingValue)"
                                    type="number" />
                                </el-form-item>
                              </el-form>
                              <div class="mar-t--10" style="text-align: right">
                                <el-button size="mini" type="text" @click="visiblePopStock = false">取消</el-button>
                                <el-button type="primary" size="mini" @click="batchUpdateSkuParamPrice">确定</el-button>
                              </div>
                              <label slot="reference" @click="editSkuParam('2')">
                                <span>库存</span>
                                <i class="el-icon-circle-plus mar-l-10 font-blue"></i>
                              </label>
                            </el-popover>
                          </template>
                        </div>
                      </th>
                      <th width="135">
                        <div class="cell text-align-c">
                          <el-popover placement="top" width="160" v-model="visiblePopGoodsBarCode">
                            <div class="text-align-c pad-b-10">批量设置</div>
                            <el-form label-position="right" style="width: 100%">
                              <el-form-item>
                                <el-input v-model="skuParamSettingValue"
                                  @keyup.native="skuParamSettingValue = checkInputPositiveNum(skuParamSettingValue)"
                                  type="number" />
                              </el-form-item>
                            </el-form>
                            <div class="mar-t--10" style="text-align: right">
                              <el-button size="mini" type="text" @click="visiblePopGoodsBarCode = false">取消</el-button>
                              <el-button type="primary" size="mini" @click="batchUpdateSkuParamPrice">确定</el-button>
                            </div>
                            <label slot="reference" @click="editSkuParam('6')">
                              <span>条形码</span>
                              <i class="el-icon-circle-plus mar-l-10 font-blue"></i>
                            </label>
                          </el-popover>
                        </div>
                      </th>
                      <th width="135">
                        <div class="cell text-align-c">外部编码</div>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <!-- 规格为1个 -->
                    <template v-if="form.qualityData.length == 1">
                      <tr v-for="(item, index) in form.singleTable" :key="index">
                        <td>
                          <div class="cell text-align-c">{{ item.skuPropValue }}</div>
                        </td>
                        <td>
                          <div class="cell text-align-c">
                            <div @click="changeImage(index)">
                              <el-upload list-type="picture-mini" action="/api/common/uploadFiles"
                                accept="image/jpeg,image/gif,image/png,image/bmp" name="files" multiple
                                v-loading="getLoading(index)" :data="token" :show-file-list="false"
                                :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                                <img v-if="item.imageUrl" :src="item.imageUrl" width="42px" height="42px"
                                  style="margin-left: -1px; margin-top: -1px" />
                                <i v-else class="el-icon-plus"></i>
                              </el-upload>
                            </div>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.scribingPrice"
                              @keyup.native=" item.scribingPrice = checkInputNum(item.scribingPrice)"
                              placeholder="请输入划线价"></el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.supplyPrice"
                              @keyup.native=" item.supplyPrice = checkInputNum(item.supplyPrice)" placeholder="请输入供应价">
                            </el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.stock" @keyup.native="item.stock = checkInputNum(item.stock)"
                              placeholder="请输入库存" :disabled="stockBoolean || form.crossBorderType === '2'"></el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.goodsBarCode" placeholder="请输入条形码"></el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.externalCode" placeholder="请输入外部编码"></el-input>
                          </div>
                        </td>
                      </tr>
                    </template>
                    <!-- 规格有2个以上 -->
                    <template v-else>
                      <tr v-for="(item, index) in form.qualityTable" :key="'info-' + index">
                        <template v-for="(subItem, subIndex) in item">
                          <template v-if="subItem.skuPropId">
                            <td :key="subIndex">
                              <div class="cell text-align-c">
                                {{ subItem.skuPropValue }}
                              </div>
                            </td>
                          </template>
                        </template>

                        <td>
                          <div class="cell text-align-c">
                            <div @click="changeImage(index)">
                              <el-upload list-type="picture-mini" action="/api/common/uploadFiles"
                                accept="image/jpeg,image/gif,image/png,image/bmp" name="files" multiple
                                v-loading="getLoading(index)" :data="token" :show-file-list="false"
                                :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                                <img v-if="item.imageUrl" :src="item.imageUrl" width="42px" height="42px"
                                  style="margin-left: -1px; margin-top: -1px" />
                                <i v-else class="el-icon-plus"></i>
                              </el-upload>
                            </div>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.scribingPrice"
                              @keyup.native="item.scribingPrice = checkInputNum(item.scribingPrice)"
                              placeholder="请输入划线价"></el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.supplyPrice"
                              @keyup.native="item.supplyPrice = checkInputNum(item.supplyPrice)" placeholder="请输入供应价">
                            </el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.stock" @keyup.native="item.stock = checkInputNum(item.stock)"
                              placeholder="请输入库存" :disabled="stockBoolean || form.crossBorderType === '2'"></el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.goodsBarCode" placeholder="请输入条形码"></el-input>
                          </div>
                        </td>
                        <td>
                          <div class="cell">
                            <el-input v-model="item.externalCode" placeholder="请输入外部编码"></el-input>
                          </div>
                        </td>
                      </tr>
                    </template>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    getToken
  } from '@/utils/auth'
  import {
    listCategorySku
  } from '@/api/goods/goods'
  import {
    getBySupplierId
  } from '@/api/user/supplier-config'
  import {
    getTaxList
  } from '@/api/warehouse/warehouseTaxItems'

  export default {
    directives: {},
    props: {
      dict: {
        type: Object
      },
      supplierGoodsId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        stockBoolean: false,
        token: '',
        fileLoading: false,
        loadingTotal: '0',
        showSingle: 1,
        form: {
          skuFlag: '0',
          stock: '',
          supplyPrice: '',
          supplierPostFee: '',
          scribingPrice: '',
          goodsBarCode: '',
          externalCode: '',
          singleTable: [],
          qualityData: [{
            skuPropId: -1,
            skuPropName: '',
            categoryId: '',
            skuPropValueList: [{
              skuPropValue: '',
              skuPropValueId: -2,
              skuPropId: -1,
              skuPropName: ''
            }]
          }],
          qualityTable: [],
          dataTable: [],
          // 供应价含税
          supplierTaxFlag: '1',
          taxItemsId: '',
          // 跨境类型：1-普通商品，2-跨境保税
          crossBorderType: '1'
        },
        ids: [],
        imageIndex: '',
        skuParamSettingValue: '',
        skuParamSettingType: '',
        visiblePopScribingPrice: false,
        visiblePopSupplyPrice: false,
        visiblePopStock: false,
        visiblePopGoodsBarCode: false,
        visiblePopExternalCode: false,
        rules: {
          supplierPostFee: [{
            max: 14,
            message: '邮费最多输入14 个字符'
          },
          {
            required: true,
            message: '请填写运费',
            trigger: 'blur'
          },
          {
            pattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/,
            message: '请正确输入邮费'
          }
          ],
          scribingPrice: [{
            max: 14,
            message: '划线价格长度最多输入 14 个字符'
          },
          {
            required: false,
            message: '请正确输入划线价格',
            trigger: 'blur'
          },
          {
            pattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/,
            message: '请填写正确金额'
          }
          ],
          supplyPrice: [{
            max: 14,
            message: '供应价最多输入14个字符'
          },
          {
            required: true,
            message: '请输入供应价',
            trigger: 'blur'
          },
          {
            pattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/,
            message: '请正确输入供应价'
          }
          ]
        },
        categoryId: '',
        categorySkuList: [],
        tempList: [],
        supplierConfig: {},
        // 税目列表
        taxList: []
      }
    },
    computed: {},
    // 初始化页面
    created() {
      this.token = {
        accessToken: getToken()
      }
      this.initGoodsEdit()
      // 获取税目信息
      this.getTaxList()
    },
    mounted() {
      const that = this
      getBySupplierId(this.getSupplierId()).then((response) => {
        if (response.isError) return
        this.supplierConfig = response.data
        if (!this.form.supplierGoodsId) {
          // 新增商品，设置默认进项税税目
          this.form.taxItemsId = this.supplierConfig.taxItemsId
        }
        if (this.supplierConfig.warehouseAuthority === 1 && this.supplierConfig.warehouseDeliverFlag === 1) {
          // 开启仓库库存，不允许编辑
          this.stockBoolean = true
        }
        this.qualityInit()
      })
      this.$bus.$on('goods_supplier.stockBoolean', function(stockBoolean) {
        that.stockBoolean = stockBoolean
      })
      this.$bus.$on('goods.edit.categoryId', function(categoryId) {
        that.categoryId = categoryId
        that.categoryChange()
      })
      this.$bus.$on('skuFlag', function(flag) {
        that.form.skuFlag = flag
      })
      that.$bus.$on('crossBorderType', function(flag) {
        that.form.crossBorderType = flag
      })
    },
    watch: {
      tempList(newVal) {
        for (const tag of this.categorySkuList) {
          tag.disabled = false
        }
        for (const tempitem of newVal) {
          for (const listitem of this.categorySkuList) {
            if (listitem.skuPropName === tempitem) {
              listitem.disabled = true
            }
          }
        }
      }
    },
    methods: {
      changeSelect(index) {
        this.tempList = []
        for (const item of this.form.qualityData) {
          if (item.categoryId !== '') {
            this.tempList.push(item.categoryId)
          }
        }
        const skuProp = this.form.qualityData[index]
        skuProp.skuPropId = this.getID()
        skuProp.skuPropValueList.forEach(skuPropValue => {
          skuPropValue.skuPropId = skuProp.skuPropId
          skuPropValue.skuPropName = skuProp.skuPropName
          skuPropValue.skuPropValueId = this.getID()
        })
      },
      addSku(item) {
        this.$prompt('请输入规格', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(({
            value
          }) => {
            const date = {
              skuPropName: value
            }
            this.categorySkuList.push(date)
            item.skuPropName = value
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            })
          })
      },
      // 删除一级规格
      removeQta(item, index) {
        if (this.form.qualityData.length > 1) {
          this.$confirm('此操作将删除该规格，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.form.qualityData.splice(index, 1)
            this.tempList.splice(index, 1)
            this.qualityInit()
          })
        }
      },
      subInputBlur() {
        if (this.form.qualityData.length === 1) {
          // 只有一个规格的，刷新一下属性名称
          const skuPropId = this.form.qualityData[0].skuPropId
          const skuPropName = this.form.qualityData[0].skuPropName
          const skuPropValueList = this.form.qualityData[0].skuPropValueList
          const singleTableList = this.form.singleTable
          for (let i = 0; i < singleTableList.length; i++) {
            singleTableList[i].skuPropId = skuPropId
            singleTableList[i].skuPropName = skuPropName
            singleTableList[i].skuPropValue = skuPropValueList[i].skuPropValue
            singleTableList[i].skuPropValueId = skuPropValueList[i].skuPropValueId
          }
          this.form.singleTable = JSON.parse(JSON.stringify(singleTableList))
        }
      },
      // 添加一级规格
      addQta() {
        const propId = this.getID()
        const valueId = this.getID()
        for (const item of this.form.qualityData) {
          if (item.skuPropName !== '') {
            this.tempList.push(item.skuPropName)
            this.tempList = Array.from(new Set(this.tempList))
          }
        }
        for (const tempitem of this.tempList) {
          for (const listitem of this.categorySkuList) {
            if (listitem.skuPropName === tempitem) {
              listitem.disabled = true
            }
          }
        }
        this.form.qualityData.push({
          categoryId: '',
          skuPropId: propId,
          skuPropName: '',
          skuPropValueList: [{
            skuPropValue: '',
            skuPropValueId: valueId,
            skuPropId: propId,
            skuPropName: ''
          }]
        })
        this.qualityInit()
      },
      // 删除子规格
      removeSubQta(item, subIndex) {
        // 子规格不能少于1个
        if (item.length > 1) {
          item.splice(subIndex, 1)
        }
        this.qualityInit()
      },
      // 添加子规格
      addSubQta(item) {
        const valueId = this.getID()
        const data = {
          skuPropValue: '',
          skuPropValueId: valueId,
          imageUrl: '',
          scribingPrice: '',
          goodsBarCode: '',
          externalCode: '',
          stock: ''
        }
        item.skuPropValueList.push(data)
        this.qualityInit()
      },
      editSkuParam(type) {
        this.skuParamSettingType = type
        this.skuParamSettingValue = ''
      },
      // 数列展示
      qualityInit() {
        if (this.form.qualityData.length === 0) {
          this.addQta()
        }
        const arrQta = []
        const itemQta = this.form.qualityData
        if (itemQta.length === 1) {
          const skuPropId = itemQta[0].skuPropId
          const skuPropName = itemQta[0].skuPropName
          const skuPropValueList = itemQta[0].skuPropValueList
          const singleTableList = this.form.singleTable
          for (let i = 0; i < skuPropValueList.length; i++) {
            if (singleTableList[i] && singleTableList[i].skuPropValueId === skuPropValueList[i].skuPropValueId) {
              skuPropValueList[i] = singleTableList[i]
            }
            skuPropValueList[i].skuPropId = skuPropId
            skuPropValueList[i].skuPropName = skuPropName
            skuPropValueList[i].stock = skuPropValueList[i].stock ? skuPropValueList[i].stock : 0
          }
          const obj = JSON.stringify(skuPropValueList)
          this.form.singleTable = JSON.parse(obj)
        } else {
          const skuCache = {}
          if (this.form.qualityTable.length > 0) {
            this.form.qualityTable.forEach((row) => {
              let item = skuCache
              for (const col in row) {
                if (row[col].skuPropValueId) {
                  if (!item[row[col].skuPropValueId]) {
                    item[row[col].skuPropValueId] = {
                      ...row
                    }
                  }
                  item = item[row[col].skuPropValueId]
                }
              }
            })
          }
          this.form.qualityTable = []
          this.showSingle = 0
          for (let i = 0; i < itemQta.length; i++) {
            const skuPropId = itemQta[i].skuPropId
            const skuPropName = itemQta[i].skuPropName
            for (let j = 0; j < itemQta[i].skuPropValueList.length; j++) {
              itemQta[i].skuPropValueList[j].skuPropId = skuPropId
              itemQta[i].skuPropValueList[j].skuPropName = skuPropName
            }
            arrQta.push(itemQta[i].skuPropValueList)
          }
          this.form.qualityTable = this.$utils.descartes(arrQta)
          if (this.form.qualityTable.length > 0) {
            const skuIdCache = {}
            const externalCodeCache = {}
            this.form.qualityTable.forEach((row, index) => {
              let item = skuCache
              for (const col in row) {
                if (row[col].skuPropValueId) {
                  if (item[row[col].skuPropValueId]) {
                    item = item[row[col].skuPropValueId]
                  }
                }
              }
              // 新增子规格，设置原来的sku的值
              if (item.skuId && !skuIdCache[item.skuId]) {
                // 新增规格不能复用skuId
                skuIdCache[item.skuId] = true
                this.$set(this.form.qualityTable[index], 'skuId', item.skuId)
              }
              if (item.supplyPrice) {
                this.$set(this.form.qualityTable[index], 'supplyPrice', item.supplyPrice)
              }
              if (item.scribingPrice) {
                this.$set(this.form.qualityTable[index], 'scribingPrice', item.scribingPrice)
              }
              if (item.goodsBarCode) {
                this.$set(this.form.qualityTable[index], 'goodsBarCode', item.goodsBarCode)
              }
              if (item.externalCode && !externalCodeCache[item.externalCode]) {
                // 新增规格不能复用外部编码
                externalCodeCache[item.externalCode] = true
                this.$set(this.form.qualityTable[index], 'externalCode', item.externalCode)
              }
              if (item.stock) {
                this.$set(this.form.qualityTable[index], 'stock', item.stock)
              } else {
                // 设置默认值
                this.$set(this.form.qualityTable[index], 'stock', '0')
              }
              if (item.imageUrl) {
                this.$set(this.form.qualityTable[index], 'imageUrl', item.imageUrl)
              }
            })
          }
        }
      },
      setQualityTable(dataTable) {
        const skuValueMap = new Map()
        for (let i = 0; i < dataTable.length; i++) {
          skuValueMap.set(dataTable[i].skuValueIds, dataTable[i])
        }

        const qualityTable = this.form.qualityTable
        const qualityData = this.form.qualityData

        if (qualityData.length === 1) {
          const skuPropValueList = qualityData[0].skuPropValueList
          const skuPropId = qualityData[0].skuPropId
          const skuPropName = qualityData[0].skuPropName

          for (let i = 0; i < skuPropValueList.length; i++) {
            skuPropValueList[i].skuPropId = skuPropId
            skuPropValueList[i].skuPropName = skuPropName
            const skuPropValueId = skuPropValueList[i].skuPropValueId
            const array = []
            array.push(skuPropValueId)
            const skuValueKey = array.sort().toString()
            const skuValueObj = skuValueMap.get(skuValueKey)
            if (!skuValueObj) {
              console.log('查无sku信息：' + skuValueKey)
              continue
            }
            if (skuValueObj.skuId) {
              skuPropValueList[i].skuId = skuValueObj.skuId
            }
            skuPropValueList[i].imageUrl = this.$utils.isExist(skuValueObj.imageUrl) ? skuValueObj.imageUrl : ''
            skuPropValueList[i].scribingPrice = this.$utils.isExist(skuValueObj.scribingPrice) ? skuValueObj
              .scribingPrice : ''
            skuPropValueList[i].goodsBarCode = this.$utils.isExist(skuValueObj.goodsBarCode) ? skuValueObj
              .goodsBarCode : ''
            skuPropValueList[i].externalCode = this.$utils.isExist(skuValueObj.externalCode) ? skuValueObj
              .externalCode : ''
            skuPropValueList[i].supplyPrice = this.$utils.isExist(skuValueObj.supplyPrice) ? skuValueObj.supplyPrice
              : ''
            skuPropValueList[i].stock = this.$utils.isExist(skuValueObj.stock) ? skuValueObj.stock : '0'
          }

          const obj = JSON.stringify(skuPropValueList)
          this.form.singleTable = JSON.parse(obj)
        } else {
          const array = []
          for (let i = 0; i < qualityTable.length; i++) {
            const item = qualityTable[i]
            const skuPropValueList = []
            for (const key in item) {
              if (this.$utils.isExist(item[key].skuPropId)) {
                const skuPropValueId = item[key].skuPropValueId
                skuPropValueList.push(skuPropValueId)
              }
            }

            const obj = {}
            const skuValueKey = skuPropValueList.sort().toString()
            const skuValueObj = skuValueMap.get(skuValueKey)
            if (skuValueObj != null) {
              if (skuValueObj.skuId) {
                obj.skuId = skuValueObj.skuId
              }
              for (const key in item) {
                obj[key] = item[key]
              }
              obj.imageUrl = this.$utils.isExist(skuValueObj.imageUrl) ? skuValueObj.imageUrl : ''
              obj.scribingPrice = this.$utils.isExist(skuValueObj.scribingPrice) ? skuValueObj.scribingPrice : ''
              obj.goodsBarCode = this.$utils.isExist(skuValueObj.goodsBarCode) ? skuValueObj.goodsBarCode : ''
              obj.externalCode = this.$utils.isExist(skuValueObj.externalCode) ? skuValueObj.externalCode : ''
              obj.supplyPrice = this.$utils.isExist(skuValueObj.supplyPrice) ? skuValueObj.supplyPrice : ''
              obj.stock = this.$utils.isExist(skuValueObj.stock) ? skuValueObj.stock : '0'
              array.push(obj)
            } else {
              console.log('sku异常' + skuValueKey)
            }
          }
          this.form.qualityTable = array
        }
      },
      categoryChange() {
        listCategorySku(this.categoryId).then((response) => {
          if (response.isError) return
          this.categorySkuList = response.data
        })
      },
      // 批量更新sku价格，库存
      batchUpdateSkuParamPrice() {
        const paramValue = this.skuParamSettingValue
        const skuParamSettingType = this.skuParamSettingType
        const qualityData = this.form.qualityData
        if (qualityData.length === 1) {
          for (let i = 0; i < this.form.singleTable.length; i++) {
            if (skuParamSettingType === '3') {
              this.visiblePopSupplyPrice = false
              this.$set(this.form.singleTable[i], 'supplyPrice', paramValue)
            } else if (skuParamSettingType === '4') {
              this.visiblePopScribingPrice = false
              this.$set(this.form.singleTable[i], 'scribingPrice', paramValue)
            } else if (skuParamSettingType === '6') {
              this.visiblePopGoodsBarCode = false
              this.$set(this.form.singleTable[i], 'goodsBarCode', paramValue)
            } else if (skuParamSettingType === '2') {
              this.visiblePopStock = false
              this.$set(this.form.singleTable[i], 'stock', paramValue || '0')
            }
          }
        } else {
          const qualityTable = this.form.qualityTable
          for (let i = 0; i < qualityTable.length; i++) {
            if (skuParamSettingType === '3') {
              this.visiblePopSupplyPrice = false
              this.$set(this.form.qualityTable[i], 'supplyPrice', paramValue)
            } else if (skuParamSettingType === '4') {
              this.visiblePopScribingPrice = false
              this.$set(this.form.qualityTable[i], 'scribingPrice', paramValue)
            } else if (skuParamSettingType === '6') {
              this.visiblePopGoodsBarCode = false
              this.$set(this.form.qualityTable[i], 'goodsBarCode', paramValue)
            } else if (skuParamSettingType === '2') {
              this.visiblePopStock = false
              this.$set(this.form.qualityTable[i], 'stock', paramValue || '0')
            }
          }
        }
      },
      getID(length) {
        const ids = this.ids
        const id = -parseInt(Math.round(Math.random() * 100000000))
        if (ids.indexOf(id) > 0) {
          this.getID()
        } else {
          ids.push(id)
          this.ids = ids
          return id
        }
      },
      changeImage(index) {
        this.imageIndex = index
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.fileLoading = true
        return isJPG || isBMP || isGIF || isPNG
      },
      getLoading(index) {
        const that = this
        if (that.loadingTotal === '1' && this.imageIndex === index) {
          return true
        } else {
          return false
        }
      },
      handleUploadSuccess(res, file) {
        this.loadingTotal = '0'
        if (res.code === 101) {
          const qualityData = this.form.qualityData
          if (qualityData.length === 1) {
            const singleTable = this.form.singleTable
            for (let i = 0; i < singleTable.length; i++) {
              const imageIndex = this.imageIndex
              if (imageIndex * 1 === i) {
                singleTable[i].imageUrl = res.data[0]
              }
            }
          } else {
            const imageIndex = this.imageIndex
            const qualityTable = this.form.qualityTable
            for (let i = 0; i < qualityTable.length; i++) {
              if (imageIndex * 1 === i) {
                qualityTable[i].imageUrl = res.data[0]
              }
            }
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
        this.$forceUpdate()
      },
      initGoodsEdit() {
        const that = this
        this.$bus.$on('goods.edit.data', function(data) {
          that.form.supplierGoodsId = data.supplierGoodsId
          that.form.goodsId = data.goodsId
          if (that.form.supplierGoodsId && that.form.goodsId) {
            // 供应商商品已经审核过，就不能再编辑sku
            that.stockBoolean = true
          }
          if (that.supplierConfig.warehouseAuthority === 1 && that.supplierConfig.warehouseDeliverFlag === 1) {
            that.stockBoolean = true
          }
          const skuFlag = that.$utils.isExist(data.skuFlag) ? data.skuFlag + '' : '0'
          that.form.skuFlag = skuFlag
          that.form.supplierPostFee = that.$utils.isExist(data.supplierPostFee) ? data.supplierPostFee : '0'
          // 供应价含税
          that.form.supplierTaxFlag = that.$utils.isExist(data.supplierTaxFlag) ? data.supplierTaxFlag.toString()
            : '1'
          // 进项税税目
          that.form.taxItemsId = that.$utils.isExist(data.taxItemsId) ? data.taxItemsId : ''
          that.form.stock = that.$utils.isExist(data.stock) ? data.stock + '' : '0'
          that.form.supplyPrice = that.$utils.isExist(data.supplyPrice) ? data.supplyPrice + '' : '0'
          that.form.scribingPrice = that.$utils.isExist(data.scribingPrice) ? data.scribingPrice + '' : ''
          that.form.goodsBarCode = that.$utils.isExist(data.goodsBarCode) ? data.goodsBarCode + '' : ''
          that.form.externalCode = that.$utils.isExist(data.externalCode) ? data.externalCode + '' : ''
          if (skuFlag === '1') {
            const qualityData = data.qualityData
            if (qualityData.length === 1) {
              const skuPropValueList = qualityData[0].skuPropValueList
              for (let i = 0; i < skuPropValueList.length; i++) {
                skuPropValueList[i].imageUrl = ''
                skuPropValueList[i].scribingPrice = ''
                skuPropValueList[i].goodsBarCode = ''
                skuPropValueList[i].externalCode = ''
                skuPropValueList[i].supplyPrice = ''
                skuPropValueList[i].stock = '0'
              }
            }
            that.form.qualityData = qualityData
            that.form.dataTable = data.qualityTable
            that.qualityInit()
            that.setQualityTable(data.qualityTable)
          }
          that.form.crossBorderType = that.$utils.isExist(data.crossBorderType)
            ? data.crossBorderType + ''
            : '1'
        })
      },
      checkForm() {
        const skuFlag = this.form.skuFlag
        // 需要校验的集合
        const checkArrays = []
        if (skuFlag * 1 === 0) {
          checkArrays.push('supplyPrice')
        }
        checkArrays.push('supplierPostFee')
        checkArrays.push('scribingPrice')
        let ret = true
        let message = ''
        this.$refs.form.validateField(checkArrays, (valid) => {
          if (valid !== '') {
            message = valid
            ret = false
            return false
          }
        })
        if (!ret) {
          this.$message({
            type: 'error',
            message: message
          })
          return false
        }
        if (skuFlag === '0') {
          if (this.stockBoolean === true && this.form.supplyPrice === '') {
            this.$message({
              type: 'error',
              message: '供应价不能为空'
            })
            return false
          }
        } else {
          // 校验属性名称是否相同
          const propNames = []
          const qualityData = this.form.qualityData
          for (let i = 0; i < qualityData.length; i++) {
            const skuPropName = qualityData[i].skuPropName
            if (!this.$utils.isExist(skuPropName)) {
              this.$message({
                type: 'error',
                message: '商品规格不能为空'
              })
              return false
            }
            const usePropValueList = []
            const skuPropValueList = qualityData[i].skuPropValueList
            for (let j = 0; j < skuPropValueList.length; j++) {
              const skuPropValue = skuPropValueList[j].skuPropValue
              if (!this.$utils.isExist(skuPropValue)) {
                this.$message({
                  type: 'error',
                  message: '商品属性不能为空'
                })
                return false
              }

              if (usePropValueList.indexOf(skuPropValue) !== -1) {
                this.$message({
                  type: 'error',
                  message: '同规格下属性名称"' + skuPropValue + '"重复'
                })
                return false
              } else {
                usePropValueList.push(skuPropValue)
              }
            }

            const propName = qualityData[i].skuPropName
            if (propNames.indexOf(propName) !== -1) {
              this.$message({
                type: 'error',
                message: '规格名称"' + propName + '"重复'
              })
              return false
            } else {
              propNames.push(propName)
            }
          }

          let table = []
          if (qualityData.length === 1) {
            const singleTable = this.form.singleTable
            table = singleTable
          } else {
            const qualityTable = this.form.qualityTable
            table = qualityTable
          }

          let stockTotal = 0
          for (let i = 0; i < table.length; i++) {
            const supplyPrice = table[i].supplyPrice
            const stock = table[i].stock
            stockTotal = stockTotal + stock

            if (!this.$utils.isExist(supplyPrice)) {
              this.$message({
                type: 'error',
                message: '商品规格供应价不能为空'
              })
              return false
            }
            if (!this.$utils.isExist(stock)) {
              this.$message({
                type: 'error',
                message: '商品库存不能为空'
              })
              return false
            }

            if (supplyPrice && supplyPrice.length > 14) {
              this.$message({
                type: 'error',
                message: '商品规格价格长度不能超过14个字节'
              })
              return false
            }
            if (stock.length > 8) {
              this.$message({
                type: 'error',
                message: '商品库存长度不能超过8个字节'
              })
              return false
            }

            // 正则表达式佣金判断
            const reg2 = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/
            const pattern2 = new RegExp(reg2)
            if (!pattern2.test(supplyPrice)) {
              this.$message({
                type: 'error',
                message: '请正确输入供应价'
              })
              return false
            }
          }

          // 正则表达式校验
          const reg = /^[0-9]*[0-9]*$/
          const pattern = new RegExp(reg)
          if (!pattern.test(stockTotal)) {
            this.$message({
              type: 'error',
              message: '请正确输入库存'
            })
            return false
          }
        }
        return true
      },
      // 获取用户的税目列表
      getTaxList() {
        getTaxList(this.getEnterpriseId()).then(response => {
          if (response.isError) {
            return
          }
          this.taxList = response.data
        })
      }
    }
  }
</script>


<style lang="less" scoped>
  .table-container {
    min-height: auto;
  }

  .quality-bar {
    background: #f2f2f2;
    border: #e4e4e4 1px solid;
    padding: 10px;

    .close-quality {
      color: #515151;
    }

    .close-sub {
      color: #aeaeae;
      position: absolute;
      right: -6px;
      top: -6px;
      font-size: 18px;
    }

    .qta-item:before {
      content: '';
      position: absolute;
      left: 12px;
      top: 34px;
      width: 1px;
      height: 46px;
      background: #bcbcbc;
    }

    .qta-item:after {
      content: '';
      position: absolute;
      left: 12px;
      top: 79px;
      width: 19px;
      height: 1px;
      background: #bcbcbc;
    }
  }

  .span-bar {
    padding: 0 50px;
  }

  .remove-btn {
    padding: 7px 6px !important;
  }

  .long-input {
    width: 80%;
  }

  .long-input-2 {
    width: 55%;
    margin-right: 5%;
  }

  .long-input-3 {
    width: 55%;
  }

  .short-input {
    width: 20%;
  }

  .short-input-2 {
    width: 25%;
  }

  .default-input {
    width: 80%;

    @media screen and (max-width: 1440px) {
      width: 100%;
    }
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }

  .picture {
    width: 130px;
    height: 130px;
    display: block;
  }

  .pic-bar {
    position: relative;

    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }

    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  .pic-add {
    background: #fff;
    border: #d3d3d3 1px dashed;
    border-radius: 5px;
    padding: 0 45px;
  }

  .input-bar-0 {
    width: 35% !important;
  }

  .input-bar-1 {
    width: 40%;
    margin-bottom: 5px !important;
  }

  .input-bar-2 {
    width: 60%;
    margin-bottom: 5px !important;
  }

  .input-bar-3 {
    width: 100%;
    margin-bottom: 5px !important;
  }

  .input-bar-4 {
    width: 35% !important;
  }

  .width-input-1 {
    width: 100% !important;
  }

  .width-input-2 {
    width: 35% !important;
  }

  .width-input-3 {
    width: 30% !important;
  }

  .width-date {
    width: 200px !important;
  }

  .gray-bar {
    background: #fff;
    padding: 5px 0 0 0;
    margin-bottom: 20px;
  }

  .gray-active {
    margin-right: 20px;
    // padding: 15px 13px;

    &.active {
      background: #fff;
    }
  }

  .radio-top-bar {
    margin-bottom: -22px;

    /deep/ .el-input-group__append,
    .el-input-group__prepend {
      padding: 0 10px;
    }
  }

  .noraml-height {
    height: 40px;
  }

  .border-d7 {
    /deep/ .el-input__inner {
      padding: 0;
      padding-left: 10px;
    }
  }
</style>
